<script setup lang="ts">
import type { DataFieldDict, DataFieldEditType, DataFieldOption } from '.'
import type { SysDict } from '@/apis/system/sysDictApi'
import { storeToRefs } from 'pinia'
import { onMounted, ref } from 'vue'
import { useDictStore } from '@/stores/dictStore'

const { dict, checkStrictly, options } = defineProps<{
  dict?: DataFieldDict
  options?: DataFieldOption[]
  disabled?: boolean
  checkStrictly?: boolean
  placeholder?: string
  editType?: DataFieldEditType
}>()
const model = defineModel<any>()
const dictStore = useDictStore()
const { dictMap } = storeToRefs(dictStore)

const isCascader = ref(false)
const items = ref<DataFieldOption[]>([])

function parseDict(dicts?: SysDict[]): DataFieldOption[] {
  const result: DataFieldOption[] = []
  if (dicts !== undefined) {
    for (const item of dicts) {
      if (dict?.dictFilter !== undefined && !dict.dictFilter(item)) {
        continue
      }
      result.push({
        value: item.dictCode!,
        label: item.dictName!,
        tagType: item.valueType === 'CUSTOM' ? item.customData?.tagType : undefined,
        tagColor: item.valueType === 'CUSTOM' ? item.customData?.tagColor : undefined,
        disabled: item.state !== 'ENABLE',
        children: parseDict(item.children),
      })
    }
  }

  return result
}

onMounted(async () => {
  if (dict) {
    await dictStore.loadDict(dict.dictCode)
    items.value = parseDict(dictMap.value[dict.dictCode])
  }
  if (items.value.length === 0 && options) {
    items.value = options
  }
  isCascader.value = items.value.filter(o => o.children && o.children.length > 0).length > 0
})
</script>

<template>
  <el-cascader
    v-if="isCascader"
    v-model="model"
    style="width: 100%;"
    :options="items"
    :props="{
      emitPath: false,
      checkStrictly,
    }"
    clearable
    filterable
    :disabled="disabled"
    :placeholder="placeholder"
  />

  <el-radio-group
    v-else-if="editType === 'button'"
    v-model="model"
    :disabled="disabled"
    :placeholder="placeholder"
  >
    <el-radio-button
      v-for="item in items" :key="item.value"
      :label="item.label" :value="item.value"
      :disabled="item.disabled"
    />
  </el-radio-group>

  <el-radio-group
    v-else-if="editType === 'radio'"
    v-model="model"
    :disabled="disabled"
    :placeholder="placeholder"
  >
    <el-radio
      v-for="item in items" :key="item.value"
      :label="item.label" :value="item.value"
      :disabled="item.disabled"
    />
  </el-radio-group>

  <el-select
    v-else
    v-model="model"
    clearable
    :disabled="disabled"
    :placeholder="placeholder"
  >
    <el-option
      v-for="item in items" :key="item.value"
      :label="item.label" :value="item.value"
      :disabled="item.disabled"
    />
  </el-select>
</template>

<style lang="css" scoped>
.el-radio-group {
  display: flex;
  flex-wrap: nowrap;
}
</style>
